package cz.cernilovsky.android.profileapp.services;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;

import cz.cernilovsky.android.profileapp.R;
import cz.cernilovsky.android.profileapp.model.Location;
import cz.cernilovsky.android.profileapp.model.Profile;
import cz.cernilovsky.android.profileapp.storage.LocationsStorage;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;

public class ProfileProcessor extends IntentService {
	private static final String TAG = "ProfileProcessor";
	
	public ProfileProcessor() {
		super("ProfileProcessor");
	}

	private static int id = 1;

	public static PendingIntent getPendingIntent(Context context) {
		Intent i = new Intent(context, ProfileProcessor.class);
		return PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		//NotificationService.notify(getApplicationContext(), "Processing intent now ...", "Got intent!");
		if(LocationClient.hasError(intent)) {
			int errorCode = LocationClient.getErrorCode(intent);
			String message = "Location Services error: " + errorCode;
			Log.e(TAG, message);
			NotificationService.notify(getApplicationContext(), message, getApplicationContext().getString(R.string.error));
		} else {
			int transitionType = LocationClient.getGeofenceTransition(intent);
			try {
				Location[] locations = LocationsStorage.loadLocations(getApplicationContext());
				List<Geofence> geofences = LocationClient.getTriggeringGeofences(intent);
				List<Location> processLocations = new ArrayList<Location>();
				for(Geofence geofence : geofences) {
					int id = Integer.parseInt(geofence.getRequestId());
					if(locations != null) {
						for(Location l : locations) {
							if(l.getId() == id) {
								processLocations.add(l);
							}
						}
					}
				}
				if(transitionType == Geofence.GEOFENCE_TRANSITION_ENTER || transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
					process(processLocations, transitionType == Geofence.GEOFENCE_TRANSITION_ENTER);
				} else {
					NotificationService.notify(getApplicationContext(), getApplicationContext().getString(R.string.wrong_transition_type), getApplicationContext().getString(R.string.error));
				}
			} catch (IOException e) {
				NotificationService.notifySettingsIOError(getApplicationContext());
				e.printStackTrace();
			} catch (JSONException e) {
				NotificationService.notifySettingsJSONError(getApplicationContext());
				e.printStackTrace();
			}
		}
	}

	private void process(List<Location> processLocations, boolean enter) {
		for(Location l : processLocations) {
			StringBuilder sb = new StringBuilder();
			boolean first = true;
			Profile[] processProfiles = enter ? l.getOnEntryProfiles() : l.getOnLeaveProfiles();
			if(processProfiles != null && processProfiles.length > 0) {
				boolean somethingProcessed = false;
				for(Profile p : processProfiles) {
					if(p.process(getApplicationContext())) {
						if(first) {
							sb.append(getString(R.string.profiles_activated) + ": ");
							first = false;
						} else {
							sb.append(", ");
						}
						sb.append(p.getName());
						somethingProcessed = true;
					}
				}
				if(somethingProcessed)
					info(l.getName(), sb.toString(), enter);
			}
		}
	}

	private void info(String locationName, String text, boolean enter) {
		NotificationService.notify(getApplicationContext(), text, getString(enter ? R.string.entered_location : R.string.left_location) + ": " + locationName);
	}

}
